package com.maserb.monitor.service.schoolForum.impl;

import com.maserb.monitor.entity.schoolForum.CommentEntity;
import com.maserb.monitor.entity.schoolForum.PostEntity;
import com.maserb.monitor.repository.schoolForum.CommentRepository;
import com.maserb.monitor.service.base.impl.JpaSpecificationServiceImpl;
import com.maserb.monitor.service.schoolForum.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;

@Service
public class CommentServiceImpl extends JpaSpecificationServiceImpl<CommentRepository,
        CommentRepository, CommentEntity, String>
        implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    private Specification<CommentEntity> getSpecification(String postId) {
        return new Specification<CommentEntity>()  {
            @Override
            public Predicate toPredicate(Root<CommentEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Join<CommentEntity, PostEntity> postJoin = root.join("post", JoinType.LEFT);
                Path<String> pathPostId = postJoin.get("id");
                ArrayList<Predicate> list = new ArrayList<Predicate>();
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathPostId, postId)));
                /*if (!StringUtils.isEmptyOrWhitespace(postId)) {

                }*/

                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
    }

    @Override
    public Page<CommentEntity> findAll(Pageable pageable, String postId) {
        return this.findAll(getSpecification(postId), pageable);
    }
}